var prefix = "/activity/manage";
var data = [];
var localTable = null;
$(function () {
    load();
    // choosedProductSkuTable();
    // initLocalTableData();
});

function load() {

    $('#productSkuTable').bootstrapTable({
            method: 'get', // 服务器数据的请求方式 get or post
            url: prefix + "/listAllSkuByProductIdNew", // 服务器数据的加载地址
            showRefresh: true,
            // showToggle : true,
            iconSize: 'outline',
            // toolbar: '#exampleToolbar',
            striped: true, // 设置为true会有隔行变色效果
            dataType: "json", // 服务器返回的数据类型
            pagination: true, // 设置为true会在底部显示分页条

            // queryParamsType : "limit",
            // //设置为limit则会发送符合RESTFull格式的参数
            singleSelect: false, // 设置为true将禁止多选
            // contentType : "application/x-www-form-urlencoded",
            // //发送到服务器的数据编码类型
            pageSize: 1000, // 如果设置了分页，每页数据条数
            pageNumber: 1, // 如果设置了分布，首页页码
            // search : true, // 是否显示搜索框
            showColumns: true, // 是否显示内容下拉框（选择显示的列）
            sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者
            // "server"
            queryParams: function (params) {
                return {
                    limit: params.limit,
                    offset: params.offset,
                    productCentreId: $.trim($("#productId").val()),
                    activityId: $.trim($("#activityId").val())
                };
            },

            columns: [
                {
                    checkbox: true
                },
                {
                    field: 'id', // 列字段名
                    title: 'ID' // 列标题
                },
                {
                    field: 'title',
                    title: 'SKU标题'
                },
                {
                    field: 'marketprice',
                    title: '价格'
                },
                {
                    field: 'stock',
                    title: '库存'
                },
                {
                    field: 'activitySkuKey',
                    title: '添加状态',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var e = '';
                        if (!row.activitySkuKey) {
                            e = e + '<a class="btn btn-warning btn-sm title="未添加"><i class="fa fa-edit"></i>未添加</a>';
                        } else {
                            e = e + '<a class="btn btn-primary btn-sm title="已添加"><i class="fa fa-edit"></i>已添加</a>';
                        }
                        return e;
                    }
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var e = '';
                        if (!row.activitySkuKey) {
                            e = e + '<a class="btn btn-primary btn-sm '
                                + '" href="#" mce_href="#" title="添加" onclick="addProductSpec(\''
                                + encodeURI(JSON.stringify(row))
                                + '\')"><i class="fa fa-edit"></i>添加</a>';
                        } else {
                            e = e + '<a class="btn btn-primary btn-sm '
                                + '" href="#" mce_href="#" title="移除" onclick="removeActivityProductSku(\''
                                + row.activitySkuKey
                                + '\')"><i class="fa fa-edit"></i>移除</a>';
                        }
                        return e;
                    }
                }]
        }
    )
    ;
}

function reLoad() {
    $('#productSkuTable').bootstrapTable('refresh');
}
function removeActivityProductSku(activityProductKey) {

    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        area: ['auto'],
        shadeClose: false,
        content: '所选中的商品移除后，将不再参加此套装？',
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            $.ajax({
                url: '/activity/manage/removeActivityProductSku',
                type: "post",
                data: {
                    'id': activityProductKey
                },
                success: function (r) {
                    if (r.code == 0) {
                        layer.alert("处理成功", {icon: 6});
                        reLoad();
                    } else {
                        layer.msg(r.msg);
                    }
                }
            });
            // })

            layer.close(index);
        }
        , cancel: function () {
            //右上角关闭回调
            return true;// 开启该代码可禁止点击该按钮关闭
        }
    });
}


function choosedProductSkuTable() {
    $('#choosedProductSkuTable').bootstrapTable('destroy');
    localTable = $('#choosedProductSkuTable').bootstrapTable({
        data: data,
        striped: true, // 设置为true会有隔行变色效果
        search: false,                      //是否显示表格搜索
        strictSearch: false,
        showColumns: false,
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "fid",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                   //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,                  //是否显示父
        columns: [
            {
                checkbox: true
            },
            {
                field: 'id', // 列字段名
                title: 'ID' // 列标题
            },
            {
                field: 'title',
                title: 'SKU标题'
            },
            {
                field: 'groupPrice',
                title: '活动价格'
            },
            {
                field: 'stock',
                title: '库存'
            },
            {
                field: 'giftAmount',
                title: '活动单次赠送件数'
            },
            {
                field: 'giftAllAmount',
                title: '活动累积赠送件数'
            },
            {
                title: '操作',
                field: 'id',
                align: 'center',
                formatter: function (value, row, index) {
                    var e = '<a class="btn btn-primary btn-sm '
                        + '" href="#" mce_href="#" title="取消参加" onclick="cancelJoin(\''
                        + value
                        + '\')"><i class="fa fa-edit"></i>取消参加</a>' +
                        '<a class="btn  btn-sm '
                        + '" href="#" mce_href="#" title="设置赠送件数" onclick="showSeckillPrice(\''
                        + value
                        + '\')"><i class="fa fa-edit"></i>设置赠送件数</a>';

                    return e;
                }
            }],
        onLoadSuccess: function () {
        },
        onLoadError: function () {
            showTips("数据加载失败！");
        }
    });
}

function initLocalTableData() {

    var that = this;
    var item = localStorage.getItem("productSKU");
    if (item) {
        var rows = JSON.parse(item);
        console.info(rows, "====")
        that.data = rows;
        reloadData();
        return;
    }

    $.ajax({
        url: prefix + "/listAllGroupByProductId",
        data: {"productCentreId": $("#productCentreId").val()},
        dataType: "json",
        success: function (data) {
            that.data = data.rows;
            reloadData();
        }
    })
}


function joinActive(rowEncode) {

}

function setting(id) {
    var rowData = getData(id);
    var rows = [];
    rows.push(rowData);
    var newData = dataCompare(rows);
    this.data = newData;
    reloadData();
    nextStep();
}

function batchSetting() {
    var h = $('#productSkuTable').bootstrapTable('getAllSelections');
    var newData = dataCompare(h);
    this.data = newData;
    reloadData();
    nextStep();
}

function nextStep() {
    $('#myTab a[href="#tab_des"]').trigger("click");
}

function cancelJoin(value) {
    var that = this;
    var tempdata = [];
    for (var i = 0; i < that.data.length; i++) {
        if (value != that.data[i].id) {
            tempdata.push(that.data[i]);
        }
    }
    that.data = tempdata;
    reloadData();
}

function dataCompare(joinData) {

    var tempdata = this.data;
    var newData = [];
    for (var i = 0; i < joinData.length; i++) {

        var b = "aa";
        for (var j = 0; j < tempdata.length; j++) {

            if (joinData[i].id == tempdata[j].id) {
                b = "bb";
            }
        }
        if (b == "aa") {

            newData.push(joinData[i]);
        }
    }
    if (newData.length > 0) {
        for (var i = 0; i < newData.length; i++) {
            tempdata.push(newData[i]);
        }
    }
    return tempdata;
}

function reloadData() {
    $('#choosedProductSkuTable').bootstrapTable('load', this.data);
}

function getData(id) {
    var rows = $("#productSkuTable").bootstrapTable('getData');//行的数据
    var rowData = {};
    var dataIndex = 0;
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].id == id) {
            rowData = rows[i];
            dataIndex = i;
            break;
        }
    }
    return rowData;
}


function showSeckillPrice(id) {

    var rows = $("#choosedProductSkuTable").bootstrapTable('getData');//行的数据
    var rowData = {};
    var dataIndex = 0;
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].id == id) {
            rowData = rows[i];
            dataIndex = i;
            break;
        }
    }

    $("#stock").val(rowData.stock);
    $("#giftAmount").val(rowData.giftAmount);
    $("#giftAllAmount").val(rowData.giftAllAmount);
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        area: ['auto'],
        shadeClose: false,
        content: $("#goodsSeckillPrice"),
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            $("#choosedProductSkuTable").bootstrapTable("updateRow", {
                index: dataIndex,//更新行索引，0起始
                replace: true,//合并or替换行数据，true替换，false合并，默认false
                row: {
                    giftAmount: $("#giftAmount").val(),//更新行数据
                    giftAllAmount: ($("#giftAllAmount").val())//更新行数据
                }
            });
            layer.close(index);
        }
        , cancel: function () {
            //右上角关闭回调
            return true;// 开启该代码可禁止点击该按钮关闭
        }
    });

}

function btnOk() {
    var rows = $("#choosedProductSkuTable").bootstrapTable('getData');//行的数据
    console.info(rows, "btnOk");

    parent.callBack(rows, 0);
    btnClose();
}

function btnClose() {
    parent.callClose();
}

function closeDow() {
    var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
    parent.layer.close(index);
}

/**
 * 没有多规格的商品编辑
 */
function addProductSpec(rowEncode) {
    var decodeRow = decodeURI(rowEncode);
    var productRow = JSON.parse(decodeRow);
    if (productRow) {
        $("#goodsName").val(productRow.title);//商品名称
        $("#goodsStock").val(productRow.total);//库存
        $("#packagePrice").val(productRow.activityPrice);//套装价格
    }
    layer.open({
        type: 1,
        title: false,
        closeBtn: 0,
        area: ['auto'],
        shadeClose: false,
        content: $("#goodsSpecSetting"),
        btn: ['确定', '取消'],
        yes: function (index, layero) {
            var activityPrice = $("#packagePrice").val();
            if (!activityPrice) {
                layer.alert("请输入套装价格", {icon: 5});
                return;
            }
            $.ajax({
                url: '/activity/manage/addActivityProductSku',
                contentType: "application/json",
                dataType: "json",
                type: 'POST',
                data: JSON.stringify({
                    activityId: $('#activityId').val(),
                    productCentreId: productRow.productCentreId,
                    skuId: productRow.id,
                    productName: productRow.title,
                    stock: productRow.total,
                    type: 5,
                    specs:productRow.specs,
                    activityPrice: $("#packagePrice").val()
                }),
                success: function (result) {
                    if (result.code == 0) {
                        layer.alert("处理成功", {icon: 6});
                        reLoad();
                    } else {
                        if (result.msg != "" && result.msg != null) {
                            layer.alert(result.msg, {icon: 5});
                        } else {
                            layer.alert("处理失败，请联系管理员", {icon: 5});
                        }
                    }
                }
            });

            layer.close(index);
        }
        , cancel: function () {
            //右上角关闭回调
            return true;// 开启该代码可禁止点击该按钮关闭
        }
    });

}

